<template>
	<section>
		<!--工具条：高级查询和新增 -->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入需要查询的信息..."></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" v-perm="'department:save'">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表：分页查询 -->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column align="center" prop="sn" label="部门编号" width="120">
      </el-table-column>
			<el-table-column align="center" prop="name" label="部门名称" width="180">
			</el-table-column>
			<el-table-column align="center" label="状态" width="120" sortable>
        <template scope="scope">
          <span style="color: #13ce66" v-if="scope.row.state==1">启用</span>
          <span style="color: #ff4949" v-else>禁用</span>
          <span style="color: #1F2D3D" v-else>未知</span>
        </template>
			</el-table-column>
			<el-table-column align="center" prop="manager.username" label="部门经理" width="150">
			</el-table-column>
			<el-table-column align="center" label="上级部门" width="150">
        <template scope="scope">
          <span style="color: hotpink" v-if="scope.row.parent">{{scope.row.parent.name}}</span>
          <span style="color: #8c939d" v-else>无上级部门</span>
        </template>
			</el-table-column>
			<el-table-column align="center" label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 批量删除 -->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-size="pageSize" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加和修改的对话框 -->
    <!--
          :title="title"  - 标题
          :visible.sync="saveFormVisible" - 控制对话框是否显示
          :close-on-click-modal="false" - 点击框外的区域不关闭
            :model="saveForm" - 表单数据是一个对象
            label-width="80px" - 标签的宽度
            :rules="saveFormRules" - 表单项验证
            ref="saveForm" - 给当前表单取一个名称 - 用来做表单验证
        -->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <!-- prop="name" ：需要验证就加上这个属性，不需要验证就不加 -->
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="部门经理">
          <!--
              seLect - 选择框
              V-model="saveForm.name” - 双向绑定
              V-for="item in managers” - item就是每一个经理对象 - employee对象
              :Label="item.username” - 回显哪一个属性值(经理的名称]
              :vaLue="item.id"> - 传递那个属性值《经理的id]
          -->
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <el-option
                v-for="item in managers"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent_id"
              :options="deptTree"
              :props="{
                checkStrictly: true,
                label: 'name', //级联框显示哪个属性
                value: 'id' //回显时需要，回传值的时候也需要
               }"
              clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
        <!--
           @click.native="saveSubmit" - 点击提交的时候调用saveSubmit方法
           :loading="saveLoading" - 提交的加载加载框
         -->
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, saveDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
        //1.分页查询相关数据
        departments: [],      //分页数据
        listLoading: false,   //加载框
        totals: 0,            //总数量
        currentPage: 1,       //当前页
        pageSize: 5,          //每页显示的条数

        //高级查询的参数
        keyword: '',

        //删除的数据
				sels: [],   //列表选中列

        //添加和修改的相关数据
        title: '',
				saveFormVisible: false, //控制对话框是否显示 - 默认不显示
				saveLoading: false, //加载框
				saveFormRules: {
					name: [
						{ required: true, message: '请输入部门名称！', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入部门编号！', trigger: 'blur' }
          ]
				},

				//编辑界面数据
				saveForm: {
					id: null,
					name: '',
					sn: '',
					state: 1,
          manager_id: null,
          parent_id: null
				},

        //下拉框的数据
        managers: [],

        //级联框实现上级部门
        deptTree: []
			}
		},
		methods: {
      //1.分页查询
      getDepartments() {
        //组装参数
        let para = {
          //分页的参数
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          //高级查询的参数
          keyword: this.keyword
        };
        //显示记载框
        this.listLoading = true;
        this.$http.post("/department", para).then(res => {
          //赋值总数量 - 计算分页栏
          this.totals = res.data.totals;
          this.departments = res.data.data;
          //隐藏加载框
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("网络繁忙，请稍后重试!!!")
        })
      },

      //防止高级查询时查询为空的现象
      keywordQuery(){
        this.currentPage = 1;
        this.getDepartments()
      },

			//删除单个数据
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => { //确认框：点击确定走then的逻辑
					this.listLoading = true;
					this.$http.delete("/department/"+row.id).then(res=>{
            this.listLoading = false;
            if (res.data.success){
              this.$message.success("删除成功！");
              //计算总页数
              var totalPage = Math.ceil(this.totals/this.pageSize);
              //删除最后一页的最后一条数据，而且不能是第一页的时候，让当前页=当前页-1
              if (this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
                this.currentPage = this.currentPage-1;
              }
              this.getDepartments();
            }else { //500异常会走这里
              this.$message.error("网络繁忙，请稍后重试！");
            }
          }).catch(res=>{ //服务器没开，404,400；这些异常会到这里
            this.$message.error("网络繁忙，请稍后重试！");
          })
				}).catch(() => {
				});
			},

      //选项改变的时候就会触发
      selsChange: function (sels) {
        this.sels = sels;
      },
      //批量删除
      batchRemove: function () {
        //获取数组中每一个对象的id，获取出来还是一个数组
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true; //显示列表的加载框
          this.$http.patch("/department",ids).then(res=>{
            if (res.data.success){
              this.$message.success("删除成功！");
              //删除后跳转到第一页
              this.currentPage=1;
              this.getDepartments();
            }else { //500异常会走这里
              this.$message.error("网络繁忙，请稍后重试！");
            }
          }).catch(res=>{ //服务器没开，404,400；这些异常会到这里
            this.$message.error("网络繁忙，请稍后重试！");
          })
        }).catch(() => {
        });
      },

      handleCurrentChange(val) {
        this.currentPage = val;
        this.getDepartments();
      },

			//点击修改按钮弹出对话框
			handleSave: function (index, row) {
        //动态修改标题
        this.title = "修改数据";
				this.saveFormVisible = true;
				//按照属性同名原则进行赋值
				this.saveForm = Object.assign({}, row);
        //调用方法获取经理的数据
        this.getManagers();
        //获取部门数
        this.getDeptTree();
			},

			//点击添加按钮弹出对话框
			handleAdd: function () {
        //动态修改标题
        this.title = "添加数据";
        this.saveFormVisible = true;
				this.saveForm = {
          id: null,
          name: '',
          sn: '',
          state: 1,
          manager_id: null,
          parent_id: null
				};
				//调用方法获取经理的数据
        this.getManagers();
        //获取部门数
        this.getDeptTree();
			},

			//点击提交 - 提交数据
			saveSubmit: function () {
        //将所有的ref表单【ref="saveForm"】，validate：验证
        //valid：只要有一个表单项验证不通过返回false，必须要所有表单项验证通过才会返回true
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						  //显示提交的加载框
							this.saveLoading = true;
							let para = Object.assign({}, this.saveForm);

							//前端无限极树的处理：null,[],[2],[2,3],1
              if (para.parent_id == null || para.parent_id.length==0){
                para.parent_id = null;
              }else if(para.parent_id.length){ //有值，没有报错，就是数组[2],[2,3]
                para.parent_id = para.parent_id[para.parent_id.length-1]
              }

							//发送请求
              this.$http.put("/department",para).then(res=>{
                //关闭提交的加载框
                this.saveLoading = false;
                //关闭对话框
                this.saveFormVisible = false;
                if (res.data.success){
                  this.$message.success("操作成功！");
                  this.getDepartments();
                }else { //500异常会走这里
                  this.$message.error("网络繁忙，请稍后重试！");
                }
              }).catch(res=>{ //服务器没开，404,400；这些异常会到这里
                this.$message.error("网络繁忙，请稍后重试！");
              })
						});
					}
				});
			},

      //获取所有的经理
      getManagers(){
        this.$http.get("/employee").then(res=>{
          //将所有的员工赋值给managers
          this.managers = res.data;
        }).catch(res=>{

        })
      },

      //获取部门数
      getDeptTree(){
        this.$http.get("/department/deptTree").then(res=>{
          this.deptTree = res.data
        }).catch(res=>{

        })
      }
		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>